package bio;

/*
 * Author: JacksonCoder
 * FileName: SocketServer
 * Version: 1.0.0
 * Date: 2025/5/6
 */

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("服务器启动，监听端口 8080...");

        while (true) {
            Socket clientSocket = serverSocket.accept();
            System.out.println("客户端连接成功：" + clientSocket.getInetAddress().getHostAddress());

            // 每个客户端用一个线程处理
            new Thread(() -> handleClient(clientSocket)).start();
        }
    }

    private static void handleClient(Socket socket) {
        try (
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))
        ) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("客户端说：" + line);

                // 处理“bye”命令，优雅关闭
                if ("bye".equalsIgnoreCase(line.trim())) {
                    writer.write("服务器：再见！");
                    writer.newLine();
                    writer.flush();
                    break;
                }

                // 回复客户端
                writer.write("服务器已收到: " + line);
                writer.newLine();
                writer.flush();
            }
        } catch (IOException e) {
            System.out.println("连接异常: " + e.getMessage());
        } finally {
            try {
                socket.close();
                System.out.println("客户端已断开连接。");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
